<script setup lang="ts">
import {version, getDocument, GlobalWorkerOptions} from 'pdfjs-dist'
import {computed, onMounted, ref, watch} from "vue";

const props = defineProps(['path', 'rotation'])
const path = computed(() => props.path)
const rotation = computed(() => props.rotation)

GlobalWorkerOptions.workerSrc = '../../../node_modules/pdfjs-dist/build/pdf.worker.mjs'
console.log(version)
const canvasBoxRef = ref()
onMounted(() => {
  renderPages(rotation.value)
})

async function renderPages(rotation) {
  const cnt = canvasBoxRef.value.children.length
  for (let i = cnt - 1; i >= 0; i--) {
    canvasBoxRef.value.removeChild(canvasBoxRef.value.children[i])
  }
  const loadingTask = getDocument(path.value)
  const pdf = await loadingTask.promise;
  for (let i = 1; i <= pdf.numPages; i++) {

    const page = await pdf.getPage(i); // 加载第一页
    const scale = 1.5

    const viewport = page.getViewport({scale, rotation: rotation});

    const canvas = document.createElement('canvas');

    canvasBoxRef.value.appendChild(canvas);

    const outputScale = window.devicePixelRatio || 1

    const context = canvas.getContext('2d');
    // canvas.height = viewport.height;
    // canvas.width = viewport.width;
    canvas.width = Math.floor(viewport.width * outputScale)
    canvas.height = Math.floor(viewport.height * outputScale)
    canvas.style.width = Math.floor(viewport.width) + 'px'
    canvas.style.height = Math.floor(viewport.height) + 'px'
    const transform = [outputScale, 0, 0, outputScale, 0, 0]

    const renderContext = {
      canvasContext: context,
      transform,
      viewport,
    };
    await page.render(renderContext).promise;
    console.log(i + "页渲染完成")
  }
  console.log("渲染完成")
}

watch(rotation, (newValue) => {
  console.log("rotation changed", newValue)
  renderPages(newValue)
})
</script>

<template>
  <div class="canvasBox" ref="canvasBoxRef"></div>
</template>

<style scoped lang="less">
.canvasBox {

  :deep(canvas) {
    display: block;
    margin-bottom: 10px;

    &:nth-last-child(1) {
      margin-bottom: 0;
    }

  }
}

@page {
  size: auto;
  margin: 3mm;
}
</style>